<script setup>
	import { onMounted, ref } from 'vue'
	import { onLoad, onShow } from '@dcloudio/uni-app'
	import { http } from '@/utils/http.js'
	import { useUsercodeStore } from '@/store/usercode.js'

	const userCodeStore = useUsercodeStore()

	const detail = ref('')
	const buynum = ref(0)
	const buyintegral = ref(0)
	const totalPrice = ref(0)
	const totalIntegral = ref(0)
	const goodsId = ref(0)
	const addressid = ref(0)
	const freight = ref(0)
	const payType = ref(3)
	const isIntegral = ref(0)
	const userIntegral = ref(0)
	const agree = ref(true)
	const addressInfo = ref({
		province: '',
		city: '',
		area: '',
		address: '',
		name: '',
		mobile: '',
	})
	async function getDetail() {
		const res = await http.request({
			url: '/api/order/createOrderPage',
			method: 'POST',
			data: {
				id: goodsId.value,
				num: Number(buynum.value),
				address_id: addressid.value,
				money: totalPrice.value,
				integral: totalIntegral.value,
			},
		})
		console.log(res)
		detail.value = res.data.data
		addressInfo.value = res.data.address_info
		addressid.value = addressInfo.value.id
		balance.value = res.data.user_balance
		userIntegral.value = res.data.user_integral
		if (res.data.freight.is_ps == 1) {
			freight.value = res.data.freight.freight
		} else {
			uni.utils.toast(res.data.freight.msg)
		}
	}
	// 地址弹窗
	const popup = ref()
	const addressList = ref()
	async function getaddressList() {
		const res = await http.request({
			url: '/api/address/myAddress',
			method: 'POST',
			data: {},
		})
		console.log(res)
		addressList.value = res.data
	}
	function addressPop() {
		getaddressList()
		popup.value.open('bottom')
	}

	//跳转管理地址
	function manageAddress() {
		uni.navigateTo({
			url: `/minePage/address/index`,
		})
		popup.value.close('bottom')
	}

	function editAddress(item) {
		uni.navigateTo({
			url: `/minePage/editaddress/index?info=${encodeURIComponent(
				JSON.stringify(item)
			)}`,
		})
		popup.value.close('bottom')
	}

	function radioChange(evt) {
		console.log(evt)
		addressid.value = evt.detail.value
		addressList.value.forEach((item) => {
			if (addressid.value == item.id) {
				console.log(item)
				addressInfo.value = item
			}
			popup.value.close('bottom')
		})
		getDetail()
	}

	//选择支付方式
	function changePay(evt) {
		payType.value = evt.detail.value
	}

	// 创建订单
	const orderId = ref(0)
	async function createOrder() {
		console.log(agree.value)
		if (!agree.value) {
			uni.utils.toast('请同意支付协议')
			return
		}
		console.log(totalPrice.value + freight.value)
		const res = await http.request({
			url: '/api/order/createOrder',
			method: 'POST',
			data: {
				id: goodsId.value,
				num: Number(buynum.value),
				address_id: addressid.value,
				money: Number(totalPrice.value),
				bz:'',
				integral: Number(
					(
						isIntegral.value == 1 && payType.value == 4 ? Number(totalIntegral.value) :Number(totalIntegral.value) + Number(freight.value)
					).toFixed(2)
				),
				pay_type: payType.value,
			},
		})
		console.log(res)
		if (res.st == 1) {
			orderId.value = res.data
			if (isIntegral.value == 1 && payType.value == 4) {
				integralPay(res.data)
			} else {
				if (payType.value == 3) {
					balancePay(res.data)
				} else if (payType.value == 1) {
					wxPay(res.data)
				}
			}
		} else {
			uni.utils.toast(res.msg)
		}
	}
	//卡尘支付
	async function balancePay(id) {
		const res = await http.request({
			url: '/api/order/balancePay',
			method: 'POST',
			data: {
				id: id,
			},
		})
		if (res.st == 1) {
			uni.utils.toast('支付成功，即将跳转到订单详情页面')
			console.log(orderId.value)
			setTimeout(() => {
				uni.reLaunch({
					url: `/homePage/paysuccess/index?id=${
						orderId.value
					}&from=${'mall'}`,
				})
			}, 2000)
		} else {
			uni.utils.toast(res.msg)
		}
	}

	//积分支付
	async function integralPay(id) {
		const res = await http.request({
			url: '/api/order/integralPay',
			method: 'POST',
			data: {
				id: id,
			},
		})
		if (res.st == 1) {
			uni.utils.toast('支付成功，即将跳转到订单详情页面')
			setTimeout(() => {
				uni.reLaunch({
					url: `/homePage/paysuccess/index?id=${
						orderId.value
					}&from=${'mall'}`,
				})
			}, 2000)
		} else {
			uni.utils.toast(res.msg)
		}
	}
	// 微信小程序微信支付
	const paying = ref(1)
	async function wxPay(id) {
		timeStatu.value = true
		const res = await http.request({
			url: '/api/adapay/adapay/adaPayOrder',
			method: 'POST',
			data: {
				id: id,
				type: 4,
			},
		})
		console.log(res)

		if (res.st == 1) {
			uni.navigateToMiniProgram({
				appId: res.data.expend.wx_app_id,
				path: res.data.expend.path,
				extraData: {},
				success(res) {
					paying.value = 2
				},
			})
		} else {
			uni.utils.toast('拉起支付失败，请联系客服~')
		}
	}

	//轮询微信支付订单状态
	const timeStatu = ref(true)
	async function askOrder() {
		setTimeout(() => {
			timeStatu.value = false
		}, 5000)
		const res = await http.request({
			url: 'api/order/getPayGoodsInfo',
			method: 'POST',
			data: {
				id: orderId.value,
			},
		})
		console.log(res)
		if (res.st == 1) {
			uni.utils.toast('支付成功，即将跳转')
			userCodeStore.setIsTrans(1)
			// setTimeout(() => {
			uni.reLaunch({
				url: `/homePage/paysuccess/index?id=${
					orderId.value
				}&from=${'mall'}`,
			})
			// }, 2000)
		} else {
			if (timeStatu.value) {
				askOrder()
			} else {
				uni.utils.toast(res.msg)
			}
		}
		paying.value = 1
	}

	//官方微信小程序微信支付
	// async function wxPay(id) {
	// 	const res = await http.request({
	// 		url: '/api/order/goodsWechatPay',
	// 		method: 'POST',
	// 		data: {
	// 			id: id,
	// 		},
	// 	})
	// 	console.log(res)

	// 	if (res.st == 1) {
	// 		uni.requestPayment({
	// 			provider: 'wxpay',
	// 			timeStamp: res.data.timeStamp, // 时间戳（单位：秒）
	// 			nonceStr: res.data.nonceStr, // 随机字符串
	// 			package: res.data.package, // 固定值
	// 			signType: res.data.signType,
	// 			paySign: res.data.paySign, // 签名，这里用的 MD5 签名
	// 			success: function (res) {
	// 				console.log('success:' + JSON.stringify(res))
	// 				if (res.errMsg == 'requestPayment:ok') {
	// 					uni.utils.toast('支付成功，即将跳转到订单详情页面')
	// 					userCodeStore.setIsTrans(1)
	// 					// setTimeout(() => {
	// 					uni.reLaunch({
	// 						url: `/homePage/paysuccess/index?id=${
	// 							orderId.value
	// 						}&from=${'mall'}`,
	// 					})
	// 					// }, 2000)
	// 				}
	// 			},
	// 			fail: function (err) {
	// 				uni.utils.toast('支付失败')
	// 				// console.log('fail:' + JSON.stringify(err))
	// 			},
	// 		})
	// 	} else {
	// 		uni.utils.toast(res.msg)
	// 	}
	// }

	// 用户信息卡尘(暂时)
	const balance = ref(0)
	//协议
	function goRule(id) {
		uni.navigateTo({
			url: `/homePage/agreement/index?id=${id}`,
		})
	}
	onLoad((option) => {
		goodsId.value = option.id
		buynum.value = option.buynum
		// addressid.value = option.address
		totalPrice.value = option.totalPrice
		isIntegral.value = option.integral
		totalIntegral.value = option.totalIntegral
		buyintegral.value = option.buyintegral
		if (isIntegral.value == 1) {
			payType.value = 4
		}
	})
	onShow(() => {
		if (paying.value == 2) {
			console.log('zouou');
			askOrder()
		}
		addressid.value = 0
		getDetail()
	})
</script>

<template>
	<view class="content">
		<view class="chooseaddress" @click="addressPop">
			<view class="addinfo">
				<view class="info">
					<text style="font-size: 24rpx">{{
						addressInfo.province +
						addressInfo.city +
						addressInfo.area
					}}</text>
					<text class="address-center">{{
						addressInfo.address
					}}</text>
					<view style="font-size: 24rpx; color: #3d3d3d"
						>{{
							addressInfo.name
						}}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<text
							style="font-size: 22rpx; color: #898989"
							>{{ addressInfo.mobile }}</text
						></view
					>
				</view>
				<view class="aim"> </view>
			</view>
		</view>
		<view class="spots">
			<view class="title">
				<view class="title-left"> 商品 </view>
			</view>
			<view class="goods">
				<image
					style="border-radius: 8rpx; width: 180rpx; height: 180rpx"
					:src="detail.img"
					mode=""
				></image>
				<view class="details">
					<view class="goods_name">
						{{ detail.goods_name }}
					</view>
					<view
						style="
							margin: 16rpx 0;
							display: flex;
							justify-content: space-between;
							align-items: end;
						"
					>
						<view style="font-size: 22rpx; color: #898989">
							规格：{{ detail.spec }}
						</view>
						<view>
							<text style="font-size: 20rpx; color: #3d3d3d"
								>X</text
							>
							<text style="font-size: 26rpx; color: #3d3d3d">{{
								buynum
							}}</text>
						</view>
					</view>
					<view>
						<image
							v-if="isIntegral == 1"
							style="
								width: 20rpx;
								height: 20rpx;
								margin-right: 10rpx;
							"
							src="../../static/icon.png"
							mode=""
						></image>
						<text v-else style="font-size: 20rpx">￥</text>
						<text v-if="isIntegral == 1" style="font-size: 28rpx">{{
							detail.integral
						}}</text>
						<text v-else style="font-size: 28rpx">{{
							detail.price
						}}</text>
					</view>
				</view>
			</view>
		</view>
		<view class="express">
			<view style="font-size: 26rpx; color: #3d3d3d; font-weight: 700">
				配送
			</view>
			<view class="money">
				<text style="margin-right: 4rpx; color: #3d3d3d">快递</text>
				<text>{{ freight == 0 ? '包邮' : `￥${freight}` }}</text>
			</view>
		</view>

		<view class="pay">
			<view class="title"> 选择支付方式 </view>
			<view class="pay-list">
				<radio-group @change="changePay">
					<view class="group-item" v-if="isIntegral == 1">
						<view>
							<radio
								style="transform: scale(0.8)"
								value="4"
								:checked="payType == 4"
							/>
						</view>
						<view
							style="
								width: 100%;
								display: flex;
								align-items: center;
								justify-content: space-between;
							"
						>
							<view style="display: flex; align-items: center">
								<image
									style="
										width: 52rpx;
										height: 52rpx;
										margin-right: 18rpx;
									"
									src="../../static/integral.png"
									mode=""
								></image>
								<text style="font-size: 24rpx">积分</text>
							</view>
							<text style="font-size: 24rpx; color: #898989">{{
								userIntegral
							}}</text>
						</view>
					</view>
					<view class="group-item" v-if="isIntegral != 1">
						<view>
							<radio
								style="transform: scale(0.8)"
								value="3"
								:checked="payType == 3"
							/>
						</view>
						<view
							style="
								width: 100%;
								display: flex;
								align-items: center;
								justify-content: space-between;
							"
						>
							<view style="display: flex; align-items: center">
								<image
									style="
										width: 54rpx;
										height: 42rpx;
										margin-right: 18rpx;
									"
									src="../../static/xinshi.png"
									mode=""
								></image>
								<text style="font-size: 24rpx">卡尘代扣</text>
							</view>
							<text style="font-size: 24rpx; color: #898989"
								>￥{{ balance }}</text
							>
						</view>
					</view>
					<view class="group-item" v-if="isIntegral != 1">
						<view>
							<radio
								style="transform: scale(0.8)"
								value="1"
								:checked="payType == 1"
							/>
						</view>
						<view
							style="
								width: 100%;
								display: flex;
								align-items: center;
								justify-content: space-between;
							"
						>
							<view style="display: flex; align-items: center">
								<image
									style="
										width: 52rpx;
										height: 52rpx;
										margin-right: 18rpx;
									"
									src="../../static/weixinpay.png"
									mode=""
								></image>
								<text style="font-size: 24rpx">微信支付</text>
							</view>
						</view>
					</view>
					<!-- <view class="group-item" v-if="isIntegral != 1">
						<view>
							<radio
								style="transform: scale(0.8)"
								value="2"
								:checked="payType == 2"
							/>
						</view>
						<view
							style="
								width: 100%;
								display: flex;
								align-items: center;
								justify-content: space-between;
							"
						>
							<view style="display: flex; align-items: center">
								<image
									style="
										width: 52rpx;
										height: 52rpx;
										margin-right: 18rpx;
									"
									src="../../static/zhifubbao.png"
									mode=""
								></image>
								<text style="font-size: 24rpx">支付宝</text>
							</view>
						</view>
					</view> -->
				</radio-group>
			</view>
		</view>
		<view class="bottom">
			<view class="bottom-left">
				<label>
					<checkbox
						@click="agree = !agree"
						value="cb"
						:checked="agree"
						color="#FFF"
						style="transform: scale(0.8)"
					/>
					<text style="font-size: 26rpx; color: #b1b0b8">同意</text>
					<text class="agree" @tap.stop="goRule(5)"
						>《平台用户服务协议》</text
					>
				</label>
				<view class="total">
					<image
						v-if="isIntegral == 1"
						style="width: 28rpx; height: 28rpx; margin-right: 10rpx"
						src="../../static/icon.png"
						mode=""
					></image>
					<text v-else style="font-size: 25rpx">￥</text>
					<text v-if="isIntegral == 1" style="font-size: 36rpx">{{
						(Number(totalIntegral) + Number(freight)).toFixed(2)
					}}</text>
					<text v-else style="font-size: 36rpx">{{
						(Number(totalPrice) + Number(freight)).toFixed(2)
					}}</text>
				</view>
			</view>
			<button type="primary" @click="createOrder">提交订单</button>
		</view>
		<!-- 地址信息弹窗 -->
		<uni-popup ref="popup" type="bottom">
			<view class="popup-content">
				<text class="title">收货地址</text>
				<scroll-view
					scroll-y="true"
					class="scroll-Y"
					style="height: 82%"
				>
					<radio-group
						@change="radioChange"
						style="
							height: 80%;
							overflow: auto;
							padding-bottom: 20rpx;
						"
					>
						<view
							class="radio"
							v-for="item in addressList"
							:key="item.address + item.id"
						>
							<view class="left">
								<radio
									style="transform: scale(0.8)"
									:value="item.id"
									:checked="item.id == addressid"
								/>
								<view class="address">
									<text style="font-size: 24rpx">{{
										item.province + item.city + item.area
									}}</text>
									<text class="address-center">{{
										item.address
									}}</text>
									<view
										style="font-size: 24rpx; color: #3d3d3d"
										>{{
											item.name
										}}&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<text
											style="
												font-size: 22rpx;
												color: #898989;
											"
											>{{ item.mobile }}</text
										></view
									>
								</view>
							</view>
							<image
								@click="editAddress(item)"
								style="width: 34rpx; height: 34rpx"
								src="../../static/edit.png"
								mode=""
							></image>
						</view>
					</radio-group>
				</scroll-view>
				<button type="primary" @click="manageAddress">地址管理</button>
			</view>
		</uni-popup>
	</view>
</template>

<style lang="scss" scoped>
	.content {
		background: #f4f4f4;
		height: 100vh;
		padding-top: 24rpx;
		.chooseaddress {
			display: flex;
			align-items: center;
			height: 160rpx;
			// margin: 24rpx 0;
			padding: 0 42rpx;
			background-color: #fff;
			box-sizing: border-box;
			.addinfo {
				width: 100%;
				display: flex;
				align-items: center;
				justify-content: space-between;
				.info {
					display: flex;
					flex-direction: column;
					margin-right: 60rpx;
				}
				.address-center {
					width: 100%;
					font-size: 28rpx;
					color: #3d3d3d;
					line-height: 62rpx;

					display: -webkit-box;
					-webkit-line-clamp: 1; /* 限制为两行 */
					-webkit-box-orient: vertical;
					overflow: hidden; /* 隐藏超出部分 */
					text-overflow: ellipsis; /* 超出部分用省略号表示 */
					white-space: normal; /* 允许换行 */
					/* 你可能还想设置一些其他样式，比如宽度、字体大小等 */
					text-align: left;
				}
				.aim {
					width: 15rpx;
					height: 15rpx;
					border-top: 1px solid #b1b0b8;
					border-right: 1px solid #b1b0b8;
					transform: rotate(45deg);
				}
			}
		}
		.spots {
			padding: 20rpx;
			padding-bottom: 60rpx;
			margin-top: 20rpx;
			background-color: #fff;
			box-sizing: border-box;
			.title {
				display: flex;
				justify-content: space-between;
				align-items: center;
				font-weight: 800;
				font-size: 26rpx;
				color: #3d3d3d;
				.title-right {
					font-size: 24rpx;
					font-weight: normal;
				}
			}
			.goods {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-top: 26rpx;
				.details {
					width: 70%;
					display: flex;
					flex-direction: column;
					justify-content: space-between;
					.goods_name {
						height: 65rpx;
						width: 100%;
						// padding: 22rpx;
						font-size: 24rpx;
						text-align: left;
						box-sizing: border-box;

						display: -webkit-box;
						-webkit-line-clamp: 2; /* 限制为两行 */
						-webkit-box-orient: vertical;
						overflow: hidden; /* 隐藏超出部分 */
						text-overflow: ellipsis; /* 超出部分用省略号表示 */
						white-space: normal; /* 允许换行 */
						/* 你可能还想设置一些其他样式，比如宽度、字体大小等 */
					}
				}
			}
			.bagGoods {
				margin-top: 26rpx;
				.scroll-view_H {
					white-space: nowrap;
					width: 100%;
					.scroll-item {
						display: inline-block;
						margin-right: 20rpx;
						&:last-child {
							margin-right: 0;
						}
						.scroll-goods-img {
							width: 160rpx;
							height: 160rpx;
							border-radius: 8rpx;
							overflow: hidden;
						}
						text {
							font-size: 22rpx;
						}
					}
				}
			}
		}
		.express {
			height: 96rpx;
			margin: 20rpx 0;
			padding: 0 22rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;
			background-color: #fff;
			box-sizing: border-box;
			.money {
				font-size: 25rpx;
				color: $all-color;
			}
		}
		.pay {
			height: 370rpx;
			padding: 26rpx;
			background-color: #fff;
			box-sizing: border-box;
			.title {
				font-weight: 800;
				font-size: 26rpx;
				color: #3d3d3d;
			}
			.group-item {
				display: flex;
				align-items: center;
				padding: 22rpx 0;
				// radio选中时背景颜色设置
				::v-deep radio .wx-radio-input.wx-radio-input-checked {
					background-color: $all-color !important;
					border: 1px solid $all-color !important;
				}
			}
		}
		.bottom {
			position: fixed;
			bottom: 0;
			display: flex;
			align-items: center;
			height: 222rpx;
			width: 100%;
			padding: 0 0 0 20rpx;
			background-color: #fff;
			box-sizing: border-box;
			.bottom-left {
				width: 70%;
				display: flex;
				flex-direction: column;
				.agree {
					font-size: 26rpx;
					color: $all-color;
				}
				::v-deep checkbox .wx-checkbox-input.wx-checkbox-input-checked {
					color: #fff;
					background: $all-color;
				}

				::v-deep .wx-checkbox-input.wx-checkbox-input-checked {
					border: 1px solid $all-color;
				}
				.total {
					margin-top: 15rpx;
					padding-left: 6rpx;
					color: $all-color;
				}
			}
			button {
				height: 66rpx;
				padding: 0 34rpx;
				border-radius: 33rpx;
				background-color: $all-color;
				font-size: 26rpx;
				line-height: 66rpx;
			}
		}
		// 地址弹出框
		.popup-content {
			align-items: center;
			justify-content: center;
			padding: 30rpx;
			height: 750rpx;
			background-color: #fff;
			border-radius: 22rpx 22rpx 0 0;
			box-sizing: border-box;
			text-align: center;
			.title {
				margin-bottom: 82rpx;
				font-size: 28rpx;
				color: #3d3d3d;
			}
			.radio {
				display: flex;
				align-items: center;
				justify-content: space-between;
				box-sizing: border-box;
				// margin-top: 26rpx;
				padding: 22rpx 0;
				border-bottom: 1px solid #f5f5f5;
				&:last-child {
					border: none;
				}
				// radio选中时背景颜色设置
				::v-deep radio .wx-radio-input.wx-radio-input-checked {
					background-color: $all-color !important;
					border: 1px solid $all-color !important;
				}
				.left {
					width: 80%;
					display: flex;
					align-items: center;
					.address {
						display: flex;
						flex-direction: column;
						align-items: start;
						margin-left: 36rpx;
						.address-center {
							width: 100%;
							font-size: 28rpx;
							color: #3d3d3d;
							line-height: 48rpx;
							text-align: left;

							display: -webkit-box;
							-webkit-line-clamp: 1; /* 限制为两行 */
							-webkit-box-orient: vertical;
							overflow: hidden; /* 隐藏超出部分 */
							text-overflow: ellipsis; /* 超出部分用省略号表示 */
							white-space: normal; /* 允许换行 */
							/* 你可能还想设置一些其他样式，比如宽度、字体大小等 */
						}
					}
				}
			}
			button {
				height: 82rpx;
				border-radius: 41rpx;
				background: $all-color;
				line-height: 82rpx;
				font-size: 28rpx;
			}
		}
	}
</style>